﻿using Castle.DynamicProxy;
using TianYuan.Core.Domain.Uow.Interception;
using TianYuan.Data.Dapper.Uow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace TianYuan.Data.Dapper.Dependency
{
   public class UnitOfWorkInterceptor: UnitOfWorkInterceptorabstract
    {
        internal readonly IUnitOfWork _unitOfWork;
        public UnitOfWorkInterceptor(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public override void Intercept(IInvocation invocation)
        {
            var NoUow= AttributeHelper.GetNoUnitOfWorkAttributeOrNull(invocation.MethodInvocationTarget);
            if (NoUow == null)//如果不存在[NoUnitOfWork]，开启事务
            {
                _unitOfWork.BeginTransaction();
            }
            
            //var disableFiltersAttr = GetDisableFiltersAttributeOrNull(invocation.MethodInvocationTarget);
            //if (disableFiltersAttr != null)
            //{
            //    List<string> filterNames = disableFiltersAttr.FilterNames.Select(filterName => filterName.ToString()).ToList();
            //    _unitOfWork.DisableFilters(filterNames.ToArray());
            //}
            //MethodInfo method = invocation.Method;
            invocation.Proceed();//先执行方法，下面再自动提交事务，如果有NoUnitOfWork属性则不提交
            //if (Attribute.IsDefined(method, typeof (NoUnitOfWorkAttribute)))
            //{
            //    return;
            //}
            //if (invocation.Method.IsDefined(typeof(NoUnitOfWorkAttribute), true))
            //{
            //    return;
            //}
            
            if (NoUow == null)//如果存在[NoUnitOfWork],不提交事务
            {
                _unitOfWork.Commit();
            }
            
        }
    }
}
